package com.rc.saas.tenant.component;

import com.rc.saas.tenant.common.vo.TResponse;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * @author frog
 * @date 2021/9/15
 */
@ControllerAdvice
public class GlobalExceptionHandlerAdvice {


    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public TResponse handler(HttpServletRequest request, ConstraintViolationException exception) {
        if (isAjaxRequest(request)) {
            StringBuffer sb = new StringBuffer();
            for (ConstraintViolation<?> constraintViolation : exception.getConstraintViolations()) {
                sb.append(constraintViolation.getMessage());
            }
            return TResponse.FAIL(sb.toString());
        }
        throw exception;
    }


    @ExceptionHandler(BindException.class)
    @ResponseBody
    public TResponse handler(HttpServletRequest request, BindException exception) throws BindException {
        if (isAjaxRequest(request)) {
            StringBuffer sb = new StringBuffer();
            BindingResult bindingResult = exception.getBindingResult();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                sb.append(fieldError.getDefaultMessage()).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            return TResponse.FAIL(sb.toString());
        }
        throw exception;
    }

    public boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest".equals(header) ? true : false;
        return isAjax;
    }
}
